﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;

namespace JwtAuth
{
    /// <summary>
    /// RabbitMQ 消费者测试
    /// </summary>
    public class WeatherFanout
    {
        public static async void Weather()
        {
            using (var connection = await RabbitUtils.GetConnection().CreateConnectionAsync())
            {
                using (var channel = await connection.CreateChannelAsync())
                {
                    await channel.ExchangeDeclareAsync("EXCHANGE_WEATHER", ExchangeType.Fanout);
                    // 声明队列信息
                    await channel.QueueDeclareAsync("QUEUE_BAIDU", true, false, false, null);
                    /*
                             * queueBind 用于将队列与交换机绑定
                             * 参数1：队列名
                             * 参数2：交换机名
                             * 参数3：路由Key(暂时用不到)
                             */
                    await channel.QueueBindAsync("QUEUE_BAIDU", "EXCHANGE_WEATHER", "");

                    await channel.BasicQosAsync(0, 1, false);

                    //创建消费者对象
                    var consumer = new AsyncEventingBasicConsumer(channel);

                    //var consumer = new EventingBasicConsumer(channel);

                    consumer.ReceivedAsync += (async (model, ea) =>
                    {
                        var message = Encoding.UTF8.GetString(ea.Body.Span);
                        Console.WriteLine($"百度收到的气象信息：{message}");
                        await channel.BasicAckAsync(ea.DeliveryTag, false);
                    });

                    await channel.BasicConsumeAsync("QUEUE_BAIDU", false, consumer);

                    Console.WriteLine("Press [Enter] to exit");
                }
            }
        }

    }
}
